﻿using Microsoft.EntityFrameworkCore;

namespace project1.Models
{
    public class OrderService
    {
        OrderDbcontext dbcontext;

        public OrderService(OrderDbcontext dbcontext)
        {
            this.dbcontext = dbcontext;
        }

        public List<Order> GetAllOrders()
        {
            return  dbcontext.Orders
                    .Include(order=>order.Details)
                    .ThenInclude(orderd=>orderd.GoodsItem)//因为goodsitem是在orderdetail之中的 所以用then
                    .Include(order=>order.oneCustomer)
                    .ToList<Order>();
        }

        public Order GetOrderById(string id)//按照订单id来查询订单 
        {
            return dbcontext.Orders
                .Include(order => order.Details)
                .ThenInclude(orderd => orderd.GoodsItem)
                .Include(order => order.oneCustomer)
                .SingleOrDefault(order => order.Orderid == id);
        }

        

        public  void AddOrder(Order order)
        {
            dbcontext.Entry(order).State = EntityState.Added;
            dbcontext.SaveChanges();
        }   

        public void RemoveOrder(string id)
        {
            var order = dbcontext.Orders
                .Include(order => order.Details)
                .SingleOrDefault (order => order.Orderid == id);
            if (order == null) return;
            dbcontext.OrderDetails.RemoveRange(order.Details);//因为orderdetail的本质是一个列表 要把这个范围内的所有列表都移除掉
            dbcontext.Orders.Remove(order);
            dbcontext.SaveChanges() ;
        }

        public void UpdateOrder(Order newOrder)
        {
            RemoveOrder(newOrder.Orderid);
            AddOrder(newOrder);
        }








    }
}
